package net.pulseproject.router.modules.logic;

import java.io.Closeable;
import java.util.Timer;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.ShortMessage;

import net.pulseproject.commons.misc.TimerTaskWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Deprecated
public class GapFiller implements SimpleListener, Closeable, Runnable {
	
	private static final Log LOG = LogFactory.getLog(GapFiller.class);
	
	
	private final SimpleListener listener;

	private final int lagTimeoutInMs;

    private Timer timer;
    
    private ShortMessage recentMessage;
    
	
	public GapFiller(final SimpleListener listener, final int lagTimeoutInMs) {
		this.listener = listener;
		this.lagTimeoutInMs = lagTimeoutInMs;
	}

	@Override
	public final synchronized void onSimpleListened(final ShortMessage message) {
		LOG.trace("onSimpleListened(message)");
		this.recentMessage = message;
		
		if(this.timer != null) {
			this.resetTimer();
		}

		this.timer = new Timer();
		this.timer.schedule(new TimerTaskWrapper(this), this.lagTimeoutInMs);
		
		this.listener.onSimpleListened(message);
	}

	@Override
	public final synchronized void run() {
		LOG.debug("run() ... creating artifical MIDI message as timeout occured.");
		this.resetTimer();
		
		final ShortMessage message = new ShortMessage();
		try {
			message.setMessage(this.recentMessage.getStatus(),
					this.recentMessage.getData1(), this.recentMessage.getData2());
		} catch (final InvalidMidiDataException e) {
			throw new RuntimeException("Could not resend midi message!", e);
		}
		
		this.recentMessage = null;
		this.listener.onSimpleListened(message);
	}

	private void resetTimer() {
		LOG.debug("resetTimer()");
		
		this.timer.cancel();
		this.timer = null;
	}

	@Override
	public final synchronized void close() {
		LOG.debug("close()");
	}
	
}
